// pages/orderconfirm/orderconfirm.js
const util = require("../../utils/util.js");
var app = getApp();
const requestManager = require("../../utils/request.js");
var router = require('../../utils/router.js');
const pageName = "PersonalCenter "
let optionsEbuyId = 0
let optionsProductId = 0
let provinceId = 0 // 地址
let data = {}
Page({
  /**
   * 页面的初始数据
   */
  data: {
    resultAddress: false, // 是否有默认地址
    detailData: null,
    addressData: null,
    totalprice: 0,
    submitdata: {
      userId: util.getUserInfo().userId,
      productId: '',
      addressId: '',
      comment: '',
      productQty: 1
    }
  },
  goAddressList() {
    let url = "/pages/AddressList/AddressList";
    router.route.setAction(router.REDIRECT_TO)
      .setParams([`ebuyId=${optionsEbuyId}&productId=${optionsProductId}`])
      .setUrl(url)
      .run()
  },
  getAddressdata(options) {
    let vm = this
    let params = {
      userId: util.getUserInfo().userId,
      channel: 'wxapp'
    }
    wx.showLoading()
    requestManager.getDataResult(requestManager.default_address, params, "GET").then(res => {
      // if (provinceId){
      let data = Object.assign({}, this.data.submitdata, {
        addressId: res.addressId
      })
      this.setData({
        addressData: res && res.addressId ? res : null,
        submitdata: data
      }, function () {
        this.getDetaildata(options.productId, options.ebuyId, options)
      })
      // wx.hideLoading()
    })
  },
  //获取商品详情数据
  getDetaildata(productid, ebuyId, options) {
    wx.showLoading()
    let params = {
      userId: util.getUserInfo().userId,
      productId: productid,
      ebuyId: ebuyId,
      channel: 'wxapp'
    }
    requestManager.getDataResult(requestManager.product_detail, params, "GET").then(res => {
      this.setData({
        totalprice: res.price,
        detailData: res
      })
      wx.hideLoading()
      if (options.provinceId) { // 如果有地址了
        let provinceId = options.provinceId
        data.mobile = util.getUserInfo().mobile
        data.ebuyId = optionsEbuyId //内购id
        data.enterpriseId = app.globalData.enterpriseId ? app.globalData.enterpriseId : '' // 企业id 判断是否可以购买
        data.contacts = options.contacts  // 收货人
        data.phone = options.phone
        data.provinceId = options.provinceId; // 省
        data.cityId = options.cityId; // 市
        data.countyId = options.countyId //区
        data.address = options.addressText
        data.productSetType = 1; // 是否是电子码用户
        data.productInfo = [
          { productId: optionsProductId, productName: res.productName, productQty: this.data.submitdata.productQty, productTotal: this.data.totalprice }
        ] // 商品信息
        data.productName = res.productName // 商品名称
        data.productQty = this.data.submitdata.productQty // 商品数量
        data.productTotal = this.data.totalprice // 商品总价 
        this.setData({
          addressData: {
            // "addressId":312,
            contacts: options.contacts,
            phone: options.phone,
            provinceId: options.provinceId,
            cityId: options.cityId,
            countyId: options.countyId,
            // "address":"海淀区测试1号",
            addressText: options.addressText
          },
          submitdata: data
        })
        console.log('thisthis...', this.data)
      } else {
        let defAddress = this.data.addressData // 默认有地址的时候
        data.mobile = util.getUserInfo().mobile
        data.ebuyId = optionsEbuyId //内购id
        data.enterpriseId = app.globalData.enterpriseId ? app.globalData.enterpriseId : '' // 企业id 判断是否可以购买
        data.contacts = defAddress.contacts  // 收货人
        data.phone = defAddress.phone
        data.provinceId = defAddress.provinceId; // 省
        data.cityId = defAddress.cityId; // 市
        data.countyId = defAddress.countyId //区
        data.address = defAddress.addressText
        data.productSetType = 1; // 是否是电子码用户
        data.productInfo = [
          { productId: optionsProductId, productName: res.productName, productQty: this.data.submitdata.productQty, productTotal: this.data.totalprice }
        ] // 商品信息
        data.productName = res.productName // 商品名称
        data.productQty = this.data.submitdata.productQty // 商品数量
        data.productTotal = this.data.totalprice // 商品总价 
        this.setData({
          submitdata: data
        })
      }
    })
  },
  // 支付事件
  handlePay() {
    let _this = this
    if (app.globalData.enterpriseId == '-1') {
      return util.noIconToast("用户当前没有内购权限哟", 3000)
    } else if (app.globalData.enterpriseId == '-2') {
      // 请先去绑定手机号
      return util.noIconToast('请先绑定手机号!', 3000)
    }
    if (!this.data.addressData) {
      return util.noIconToast('请添加地址!', 3000)
    }
    let params = this.data.submitdata
    params.productInfo[0].productQty = this.data.submitdata.productQty
    params.productInfo[0].productTotal = this.data.totalprice
    requestManager.getDataResult(requestManager.order_confirm, params, "POST").then(res => {
      console.log('确认订单...', res.data.payInfo)
      let payData = res.data.payInfo
      wx.requestPayment({
        timeStamp: payData.timeStamp,
        nonceStr: payData.nonceStr,
        package: payData.package,
        signType: 'MD5',
        paySign: payData.paySign,
        success(ress) {
          // 跳转到支付成功
          let url = "/pages/paysuccess/paysuccess";
          router.route.setAction(router.NAVIGATE_TO)
            .setParams([`productId=${data.productid}&productTotal=${_this.data.totalprice}`])
            .setUrl(url)
            .run()
        },
        fail(res) {
          console.log(res)
        }
      })
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.getAddressdata(options)
    optionsEbuyId = options.ebuyId
    optionsProductId = options.productId
    data = Object.assign({}, this.data.submitdata, {
      productId: options.productId
    })
  },
  handleAdd() {
    var currentNum = this.data.submitdata.productQty
    currentNum++
    let currentPrice = this.data.detailData.price
    let data = Object.assign({}, this.data.submitdata, {
      productQty: currentNum
    })
    data.productTotal = Number(currentPrice * currentNum).toFixed(2)
    this.setData({
      submitdata: data,
      totalprice: Number(currentPrice * currentNum).toFixed(2)
    })
  },
  handleMinus() {
    var currentNum = this.data.submitdata.productQty
    if (currentNum > 0) {
      currentNum--
      let data = Object.assign({}, this.data.submitdata, {
        productQty: currentNum
      })
      let currentPrice = this.data.detailData.price
      data.productTotal = Number(currentPrice * currentNum).toFixed(2)
      this.setData({
        submitdata: data,
        totalprice: Number(currentPrice * currentNum).toFixed(2)
      })
    }
  },
  bindTextAreaBlur(e) {
    let data = Object.assign({}, this.data.submitdata, {
      comment: e.detail.value
    })
    data.comment = e.detail.value
    this.setData({
      submitdata: data
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})